<template>
  <!-- 固定属性 -->
  <div>
    <el-row>
      <el-col :span="24">
        <el-select :disabled="disabledFlag" v-model="limitType" :placeholder="$t('请选择')" @change="changeStatus" value-key="code">
          <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-col>
      <el-col :span="24" v-if="limitType == 2">
        <!-- v-if="loading" -->
        <el-form ref="form" :model="form" label-width="0" :rules="rules" :disabled="type == 3">
          <el-row v-for="(item, index) in form.propertyInfos" :key="index">
            <el-col :span="24">
              <!-- 固定属性名 -->
              <el-form-item label="" :prop="`propertyInfos.${index}.propertyCode`" :rules="limitType == 2 ? rules.validateInfo : { required: false }" label-width="0">
                <el-select v-model="item.propertyCode" @change="changeProperty(1, $event, index)" value-key="spuFactorCode">
                  <el-option v-for="(item, index) in propertyNameList" :key="Math.random()" :label="item.spuFactorName" :value="item.spuFactorCode"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="visible">
              <!-- 固定属性值 -->
              <el-form-item label="" :prop="`propertyInfos.${index}.propertyValue`" :rules="limitType == 2 ? rules.validateInfo : { required: false }" label-width="0">
                <el-popover v-if="readonly && item.propertyValue && item.propertyValue.length > 0" placement="top" title="" width="400" trigger="hover">
                  <ul>
                    <li v-for="(it, i) in item.propertyValue" :key="i">
                      {{ it }}
                    </li>
                  </ul>
                  <template slot="reference">
                    <el-select v-model="item.propertyValue" @change="changeData" multiple collapse-tags>
                      <el-option v-for="(it, idx) in item.propertyValueList" :key="idx" :label="it" :value="it"></el-option>
                    </el-select>
                  </template>
                </el-popover>
                <el-select v-else v-model="item.propertyValue" @change="changeData" multiple collapse-tags>
                  <el-option v-for="(it, idx) in item.propertyValueList" :key="idx" :label="it" :value="it"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <img style="cursor: pointer; margin-top: 7px" src="@/assets/images/del_icon.png" width="16px" height="18px" @click="handledel(index)" v-if="type != 3 && form.propertyInfos.length > 1" />
            </el-col>
          </el-row>
          <el-button type="text" class="el-icon-plus" @click="handleAdd" v-if="type != 3 && form.propertyInfos.length < 5">{{ $t('添加') }}</el-button>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import nonStandardService from '@/services/nonStandardService'
import eventBus from '@/assets/utils/eventBus.js'
export default {
  name: 'fixedTypes',
  props: {
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: [Object, String],
    disabled: Boolean,
    parameter: {
      type: Object,
      default: () => {
        return {}
      }
    },
    type: Number,
    data: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      statusList: [
        { value: 1, label: this.$t('不限') },
        { value: 2, label: this.$t('指定') }
      ],

      options: [],
      warehouseId: null,
      checkedData: [],
      categoryCode: null,
      form: {
        propertyInfos: [{}]
      },
      readonly: false,
      rules: {
        validateInfo: [{ required: true, message: this.$t('请选择'), trigger: 'change' }]
      },
      propertyNameList: [],
      spuFactorCode: null,
      spuId: null,
      loading: false,
      limitType: 1,
      visible: true,
      disabledFlag: false
    }
  },
  created() {
    if (this.type == 1) {
      this.$emit('input', String(this.limitType))
    }
    eventBus.$on('changeValue', () => {
      this.$nextTick(() => {
        if (this.limitType == 1) {
          this.$emit('input', String(this.limitType))
        }
      })
    })
    this.readonly = Boolean(this.$route.query.readonly)
    eventBus.$on('categoryChange', (data) => {
      this.form.propertyInfos = [{}]
      this.checkedData = null
      if (data.spuId) {
        this.spuId = data.spuId
        this.queryPropertyName()
      } else {
        this.spuId = null
      }
      if (data.multipleFlag) {
        this.disabledFlag = true
        this.limitType = 1
        this.$emit('input', String(this.limitType))
      } else {
        this.disabledFlag = false
      }
    })
    if (this.value) {
      this.setData()
    }
  },
  methods: {
    /** 获取属性名数据
     * 指定品名 获取指定属性
     * 不限 则可获取所有属性
     */
    queryPropertyName() {
      if (this.spuId) {
        nonStandardService.queryType({ spuId: this.spuId }).then((res) => {
          if (res.code == 200) {
            this.propertyNameList = []
            this.propertyNameList = res.data.attrListTypeList
          }
        })
      } else {
        nonStandardService.queryPropertyList({ tenantId: localStorage.getItem('tenantId') }).then((res) => {
          if (res.code == 200) {
            this.propertyNameList = []
            this.propertyNameList = res.data
          }
        })
      }
    },
    /** 获取属性值数据
     * 指定品名 获取指定属性值
     * 不限 则可获取所有属性值
     */
    queryPropertyValue(index, propertyCode) {
      this.visible = false
      if (this.spuId) {
        nonStandardService
          .queryListBySpuId({
            spuId: this.spuId,
            spuFactorCode: this.spuFactorCode ? this.spuFactorCode : propertyCode
          })
          .then((res) => {
            if (res.code == 200) {
              if (!this.form.propertyInfos[index]) {
                this.form.propertyInfos[index] = {}
                this.form.propertyInfos[index].propertyValueList = []
              }
              this.form.propertyInfos[index].propertyValueList =
                res.data &&
                res.data.map((it) => {
                  return it.spuFactorValue
                })
              this.visible = true
              this.$forceUpdate()
            }
          })
      } else {
        nonStandardService
          .queryFullList({
            spuFactorCode: this.spuFactorCode ? this.spuFactorCode : propertyCode,
            pageNum: 1,
            pageSize: 9999
          })
          .then((res) => {
            if (res.code == 200) {
              if (!this.form.propertyInfos[index]) {
                this.form.propertyInfos[index] = {}
                this.form.propertyInfos[index].propertyValueList = []
              }
              this.form.propertyInfos[index].propertyValueList =
                res.data.list &&
                res.data.list.map((it) => {
                  return it.spuFactorValue
                })
              this.visible = true
              this.$forceUpdate()
            }
          })
      }
    },
    changeProperty(type, data, index) {
      if (type == 1) {
        this.form.propertyInfos[index].propertyValue = undefined
        this.spuFactorCode = data ? data : this.spuFactorCode
        this.queryPropertyValue(index)
        let flag = this.form.propertyInfos.some((it, idx) => index != idx && it.propertyCode == data)
        if (flag) {
          this.$message.error(this.$t('固定属性不可重复'))
          this.$set(this.form.propertyInfos[index], 'propertyCode', null)
          return
        }
        let info = this.propertyNameList.find((it) => it.spuFactorCode == this.spuFactorCode) || {}
        this.form.propertyInfos[index].propertyName = info.spuFactorName
      }
    },
    handleAdd() {
      this.form.propertyInfos.push({})
      this.$forceUpdate()
    },
    handledel(index) {
      this.form.propertyInfos.splice(index, 1)
      this.$forceUpdate()
    },
    setData() {
      let categoryData = this.data.category.indexOf('{') === 0 ? JSON.parse(this.data.category) : {}
      if (categoryData.spuId) {
        this.spuId = categoryData.spuId
      }
      if (categoryData.checkedData && categoryData.checkedData.length > 1) {
        this.spuId = null
        this.disabledFlag = true
      }
      this.queryPropertyName()
      let data = JSON.parse(this.value)
      this.limitType = data.limitType
      localStorage.setItem('propertyType', this.limitType)
      this.form.propertyInfos =
        data.propertyInfos &&
        data.propertyInfos.map((it, index) => {
          if (it.propertyCode) {
            this.queryPropertyValue(index, it.propertyCode)
          }
          return {
            ...it,
            propertyValue: it.propertyValue ? it.propertyValue.split(',') : ''
          }
        })
    },
    changeStatus(val) {
      this.form.propertyInfos = [{}]
      /**状态改变，判断价格优先级 */
      eventBus.$emit('statusChange')
      if (val == 1) {
        this.$emit('input', String(val))
      } else {
        this.queryPropertyName()
        this.$emit('input', '')
      }
      localStorage.setItem('propertyType', val)
      /**状态改变，判断价格优先级 */
      eventBus.$emit('statusChange')
    },
    changeData(val) {
      this.$refs.form.validate().then(() => {
        this.$emit('input', String(this.limitType))
      })
      if (val && val.length == 0) {
        this.$emit('input', '')
      }
    },
    getData() {
      let propertyInfos =
        this.form.propertyInfos &&
        this.form.propertyInfos.map((it) => {
          return {
            propertyName: it.propertyName,
            propertyValue: it.propertyValue ? it.propertyValue.join(',') : null,
            propertyCode: it.propertyCode
          }
        })
      return {
        limitType: this.limitType,
        propertyInfos
      }
    }
  }
}
</script>
